package com.sxc.oa.web.action;

import com.sxc.oa.utils.Dbutil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DepListServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应的内容类型以及字符集，防止中文乱码问题。
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print("<!DOCTYPE html>");
        out.print("<html lang='en'>");
        out.print("<head>");
        out.print("<meta charset='UTF-8'>");
        out.print("<meta name='viewport' content='width=device-width, initial-scale=1.0'>");
        out.print("<title>部门列表页面</title>");
        out.print("</head>");
        out.print("<body>");
        out.print("<h1 align='center'>部门列表</h1>");
        out.print("<hr>");
        out.print("<table border='1px' align='center' width='50%'>");
        out.print("<tr>");
        out.print("<th>序号</th>");
        out.print("<th>部门编号</th>");
        out.print("<th>部门名称</th>");
        out.print("<th>操作</th>");
        out.print("</tr>");
        //以上部分是不动的

        //连接数据库，查询所有的部门
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 获取链接
            conn = Dbutil.getConnction();

            // 获取预编译的数据库操作对象
            String sql = "select deptno as a,dname,loc from dept";
            ps = conn.prepareStatement(sql);

            // 执行SQL语句
            rs = ps.executeQuery();

            int i = 0;
            while (rs.next()) {

                String deptno = rs.getString("a");
                String dname = rs.getString("dname");
                String loc = rs.getString("loc");
                out.print("--------------");
                out.print("<tr>");
                out.print("<td>"+(++i)+"</td>");
                out.print("<td>"+deptno+"</td>");
                out.print("<td>"+dname+"</td>");
                out.print("<td>"+loc+"</td>");
                out.print("<td>");
                out.print("<a href=''>delete</a>");
                out.print("<a href='edit.html'>change</a>");
                out.print("<a href='detail.html'>detail</a>  ");
                out.print("</td>");
                out.print("</tr>");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭资源
            try {
                Dbutil.close(conn, ps, rs);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        }

    }

